import window from ".";
import _ from "lodash";
import { WeaLocaleProvider } from 'ecCom';
import searchStores, { SearchDisplayType } from '../stores/list';
import { toJS } from "mobx";

const getLabel = WeaLocaleProvider.getLabel;
import { modeForm_pc } from './excelUtil2';

export const modeList = {
    // dialogObj: undefined,
    /****获取当前查询类型
     *  Excel = 'excel',
     *  Normal = 'normal',
      *  TreeType = 'treeType', 分组列表
      *  ImgType = 'imgType'  相册列表
      *  VerticalType = 'verticalType',  //纵向列表
      */
    getSearchCurrentType: function () {
        let type: string = searchStores.displayType || 'normal';
        if (searchStores.displayType === SearchDisplayType.ImgType) {
            type = SearchDisplayType.ImgType;
        } else if (searchStores.displayType == SearchDisplayType.Excel) {
            type = SearchDisplayType.Excel;
        } else if (searchStores.displayType == SearchDisplayType.TreeType) {
            type = SearchDisplayType.TreeType;
        }else if (searchStores.displayType == SearchDisplayType.VerticalType) {
            type = SearchDisplayType.VerticalType;
        }
        return type;
    },
    /**
     *  选中的checkbox的值（主表数据ID)
     *  返回值说明： 多个数据ID以英文半角逗号分开
     *  返回例子： 1,2,3,4
     *  支持环境： normal/treetype/imgtype
     */
    getCheckedID: function () {
        if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
            let ids: string = '';
            if (searchStores.treeKey) {
                ids = _.uniq(searchStores.treeKey.map(d => d.split('_')[0])).join(",");
            }
            return ids;
        } else if (this.getSearchCurrentType() === SearchDisplayType.ImgType) {
            if (searchStores.selectRowkeys && searchStores.selectRowkeys.length > 0) {
                return searchStores.imgSelectValue;
            }
            return '';
        }else if (this.getSearchCurrentType() === SearchDisplayType.VerticalType) {
            if (searchStores.selectRowkeys && searchStores.selectRowkeys.length > 0) {
                return searchStores.verticalListStore.selectValue;
            }
            return '';
        }else if (this.getSearchCurrentType() === SearchDisplayType.Excel) {
            return window._xtable_CheckedCheckboxId();
        }  else {
            var allIds = searchStores.newTable.selectedRowKeysAllPages;
            allIds = _.map(allIds, d=>d.split('_')[0]);
            /*var selectedIds = searchStores.newTable.datas.filter(d => allIds.indexOf(this.getListKey(d)) > -1)
                .map(d => d.randomFieldId);*/
            return _.uniq(allIds).join(',');
        }
    },

    getTitleVal: function () {
        return getLabel(16641, "高效源于协同");
    },

    /**
     *  选中的checkbox的带有明细的值（主表数据ID_明细数据ID)
     *  返回值说明： 多个数据ID以英文半角逗号分开；如果没有明细格式：主表数据ID + “_”
     *  返回例子： 1_1,1_2,2_1 ；当不存在明细：1_
     *  支持环境： normal/treetype/imgtype
     */
    getCheckedIDWithDetail: function () {
        let ids = new Array();
        if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
            if (searchStores.treeKey) {
                ids = this.handleIds(_.uniq(searchStores.treeKey));
            }
        } else if (this.getSearchCurrentType() === SearchDisplayType.ImgType || this.getSearchCurrentType() === SearchDisplayType.VerticalType) {
            let allIds = toJS(searchStores.selectRowkeys) || [];
            ids = this.handleIds(allIds);
        } else {
            ids = searchStores.newTable.selectedRowKeysAllPages;
        }
        return _.uniq(ids).join(',');
    },
    /***分组列表数据处理ids */
    handleIds: function (datas = []) {
        const idarrs = new Array();
        _.forEach(datas, (id: string) => {
            if (id.indexOf('_') < 0) {
                idarrs.push(id + '_')
            } else {
                idarrs.push(id)
            }
        });
        return idarrs;
    },

    /***获取分组列表的所有数据id */
    getAllTreeListIds: function () {
        const idarrs = new Array();
        const datas = toJS(searchStores.tableData.Data);
        const loop = data => data.map((item) => {
            if (item.sublist && item.sublist.length > 0) {
                idarrs.push(item.key);
                return loop(item.sublist);
            }
            return idarrs.push(item.key);
        });
        loop(datas);
        return _.uniq(idarrs);
    },
    /**
     * 未选中的checkbox的值（主表数据ID)
     * 返回值说明： 多个数据ID以英文半角逗号分开
     * 返回例子： 1,2,3,4
     * 支持环境： normal/treetype/imgtype
     */
    getUnCheckedID: function () {
        var ids
        if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
            const allids = this.getAllTreeListIds();
            let checkids = new Array();
            if (searchStores.treeKey) {
                checkids = _.uniq(searchStores.treeKey);
            }
            return _.uniq(allids.filter(d => checkids.indexOf(d) == -1).map(d => d.split('_')[0]).join(","));
        }
        if(this.getSearchCurrentType() === SearchDisplayType.VerticalType){
            let allIds = toJS(searchStores.selectRowkeys) || [];
            ids = this.handleIds(allIds);
            const  unIds = searchStores.verticalListStore.allDatas.filter(d => ids.indexOf(this.getListKey(d)) == -1)
                .map(d => d.randomFieldId);
            return _.uniq(unIds).join(',');
        }
        if (this.getSearchCurrentType() === SearchDisplayType.ImgType) {
            let allIds = toJS(searchStores.selectRowkeys) || [];
            ids = this.handleIds(allIds);
        } else {
            ids = searchStores.newTable.selectedRowKeys;
        }
        var unIds = searchStores.newTable.datas.filter(d => ids.indexOf(this.getListKey(d)) == -1)
            .map(d => d.randomFieldId);
        return _.uniq(unIds).join(',');
    },

    /**
     *  未选中的checkbox的带有明细的值（主表数据ID_明细数据ID)
     *  返回值说明： 多个数据ID以英文半角逗号分开, 如果没有明细格式：主表数据ID + “_”
     *  返回例子： 1_1,1_2,2_1; 当不存在明细：1_
     *  支持环境： normal/treetype/imgtype
     */
    getUnCheckedIDWithDetail: function () {
        var ids;
        if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
            const allids = this.getAllTreeListIds();
            let checkids = new Array();
            if (searchStores.treeKey) {
                checkids = _.uniq(searchStores.treeKey);
            }
            const ids = _.uniq(allids.filter(d => checkids.indexOf(d) == -1));
            return this.handleIds(ids).join(',')
        }
        if(this.getSearchCurrentType() === SearchDisplayType.VerticalType){
            let allIds = toJS(searchStores.selectRowkeys) || [];
            ids = this.handleIds(allIds);
            const  unIds = searchStores.verticalListStore.allDatas.filter(d => ids.indexOf(this.getListKey(d)) == -1)
            .map(d => this.getListKey(d));
            return _.uniq(unIds).join(',');
        }
        if (this.getSearchCurrentType() === SearchDisplayType.ImgType) {
            let allIds = searchStores.getAllImgListIds();
            let checkids = new Array();
            if (searchStores.selectRowkeys) {
                checkids = _.uniq(searchStores.selectRowkeys);
            }
            ids = _.uniq(allIds.filter(d => checkids.indexOf(d) == -1));
            return this.handleIds(ids).join(',');
        } 
        
        ids = searchStores.newTable.selectedRowKeys;
        
        var unIds = searchStores.newTable.datas.filter(d => ids.indexOf(this.getListKey(d)) == -1)
            .map(d => this.getListKey(d));
        return _.uniq(unIds).join(',');
    },

    /**
     * 清除选中的checkbox
     *
     */
    clearChecked: function () {
        if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
            return searchStores.setSelectedRowKeys([], [])
        }
        return window._xtable_CleanCheckedCheckbox();
    },

    /**
     *  全选
     */
    setAllChecked: function () {
        this.clearChecked();
        if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
            const allids = this.getAllTreeListIds();
            searchStores.setSelectedRowKeys(allids, [])
        } else {
            if (this.getSearchCurrentType() === SearchDisplayType.ImgType) {
                searchStores.selectRowKeyAll();
            }else if (this.getSearchCurrentType() === SearchDisplayType.VerticalType) {
                searchStores.verticalListStore.selectRowKeyAll();
            }else{
                searchStores.newTable.setSelectedRowKeys(this.getUnCheckedIDWithDetail().split(","));

            }
        }
    },

    /**
     * 重新加载表格
     */
    reloadTable: function () {
        if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
            searchStores.refresh();
        } else if (this.getSearchCurrentType() === SearchDisplayType.ImgType || this.getSearchCurrentType() === SearchDisplayType.VerticalType ) {
            searchStores.refresh();
        } else {
            window._table.reLoad();
        }
    },
    /**
     * 重新加载表格--全部数据
     */
    reloadTableAll: function () {
        searchStores.refresh();
        // if (this.getSearchCurrentType() === SearchDisplayType.TreeType) {
        //     searchStores.refresh();
        // }else if (searchStores.displayTypeForImg && this.getSearchCurrentType() === SearchDisplayType.ImgType) {
        //     searchStores.refresh();
        // } else {
        //     searchStores.refresh();
        // }
    },
    /**
     * 获取查询列表Id
     */
    getCustomID: function () {

        return searchStores.customId;
    },

    /**
     * 获取查询列表对应表单ID
     */
    getFormID: function () {

        return searchStores.formId;
    },

    /**
     * 获取查询列表对应模块ID
     */
    getModeID: function () {

        return searchStores.modeId;
    },

    /**
     *  获取查询列表Id+模块Id+表单Id
     *  返回格式{customId:customId,formId:formId,modeId:modeId}
     */
    getCustomIdWithModeIDAndFormID: function () {

        return {
            customId: searchStores.customId,
            formId: searchStores.formId,
            modeId: searchStores.modeId
        }
    },

    /**
     *  获取查询列表url地址中的参数
     *  返回格式{customid: customid,guid: guid,_key: _key}
     */
    getListUrlInfo: function () {
        return toJS(searchStores.params)
    },

    /**
     *
     * 获取当页表格json数据
     */
    getTableDatas: function () {
        return toJS(searchStores.newTable.datas).map(o =>
            _.pick(o, _.keys(o).filter(fieldName => !fieldName.endsWith("span") && !_.eq("span", fieldName))
            )
        )
    },

    /**
     *
     * 获取当页表格json数据
     */
    getTableDatasWithSpan: function () {

        return toJS(searchStores.newTable.datas);
    },


    getListKey: function (data) {
        if ('randomFieldSubKeyd_id' in data) { // 明细ID
            // 相册单独处理
            if (this.getSearchCurrentType() === SearchDisplayType.ImgType ||this.getSearchCurrentType() === SearchDisplayType.VerticalType) {
                return data.randomFieldSubKeyd_id ? `${data.randomFieldId}_${data.randomFieldSubKeyd_id}` : `${data.randomFieldId}`
            } else {
                return `${data.randomFieldId}_${data.randomFieldSubKeyd_id}`;
            }
        } else {
            return `${data.randomFieldId}`;
        }
    },

    /**
     * dataLoadAfter的回调函数,对列表的数据进行二次加工，并渲染
     * @param datas (array) 列表数据
     * @param displayType (string) normal 普通列表,excel 表格视图,treeType 树形列表
     */
    dataLoadAfterCB: null,

    /**
     * 对列表的数据进行二次加工，并渲染
     */
    dataLoadAfter: function (callback) {
        this.dataLoadAfterCB = callback;
    },

    /***
     * 打开一个自定义对话框
     */
    openCustomDialog: function (prop, buttons?) {
        window.modeForm.openCustomDialog(prop, buttons);
    },
    /**
     * 关闭指定的自定义对话框
     */
    closeCustomDialog: function () {
        window.modeForm.closeCustomDialog();
    },
    /**
    *
    * 自定义查询
    */
    customSearch: function (condition) {
        searchStores.customSearch(condition);
    },
    /****
     * 打开侧滑窗口
     */
    slideOpenModal: function (bool, url, sliderPercentage = 70) {
        searchStores.showSlideModal(bool, url, sliderPercentage);
    },
    /***
     * 获取批量修改的字段值
     */
    getBatchEditDatas: function () {
        try {
            return toJS(searchStores.editTableStore.form.$('tableForm').values());
        } catch (error) {

        }
    },
    /***
    * 获取当前查询条件的值
    */
    getHighSearchDatas: function () {
        try {
            return toJS(searchStores.condition.form.values());
        } catch (error) {

        }
    },
    /***
    * 获取顶部查询条件的值
    */
    getTopSearchDatas: function () {
        try {
            return toJS(searchStores.quickSearchFormData);
        } catch (error) {

        }
    },

    /***
     * 控制全局spin的开始与结束
     */
    showLoading: function (bool, size?, tip?) {
        searchStores.showGlobalSpin = {
            isShow: bool ? 'show' : 'hide',
            size: size || 'defalut',
            tip: tip || '',
        }
    },
    /***右键-导出 */
    getAllExcelOut: function (billid: string) {
        searchStores.getAllExcelOut(billid);
    },
    /***调用右键事件
    * 系统按钮：type= functionname
    * 页面扩展 type = doCustomFunction,expendid,name,必填一个，先走前面的id
    */
    doRightBtnEvent: function (type, expendid?, name?) {
        try {
            const rightMenu = toJS(searchStores.rightMenus);
            let btnObj = type;
            let pageid;
            if (type === 'doCustomFunction') { //自定义按钮
                if (expendid) {
                    pageid = expendid;
                } else if (name) {  //支持多语言。eg：商务管理~~Business~~商務管理
                    const names = name.split('~~');
                    rightMenu && rightMenu.map(item => {
                        if (_.indexOf(names, item.name) >= 0) {
                            btnObj = item;
                            pageid = item.key;
                        }
                    });
                } else {
                    this.showMessage('请填写指定的页面扩展id或者名称！');
                }
            } else {
                rightMenu && rightMenu.map(item => {
                    let _fun = item.function; //"submitData"
                    if (type === _fun) {
                        btnObj = item;
                        pageid = item.key;
                    }
                });
            }
            if (btnObj && pageid) {
                searchStores.rightMenuClick(pageid);
            }
        } catch (e) {
        }
    },

    /**加下公共的全局的方法 */
    ...modeForm_pc

}
